package com.xiaoliang.servlet;


import com.xiaoliang.entry.User;
import com.xiaoliang.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

/**
 * @author XIAOLIANG
 * @ClassName Login.java
 * @Description TODO
 * @createTime 2021年02月20日 17:54:00
 */

public class Login extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		System.out.println("进入登录servlet");

		HttpSession session = req.getSession();
		String code = req.getParameter("code");

		Object verificationCode = session.getAttribute("verificationCode");  //获取验证码
		String realCode = String.valueOf(verificationCode);

		if (realCode!=null&&realCode.equalsIgnoreCase(code)){                         //先判断验证码是否正确 再进行账号的判断
			String username = (String) req.getParameter("username");
			String password = (String) req.getParameter("password");

			UserServiceImpl userService = new UserServiceImpl();

			boolean loginAccess = userService.login(new User(username, password));

			if (loginAccess){
				session.setAttribute("username",username);
				session.setAttribute("login","ok");
				resp.sendRedirect(req.getContextPath()+"/product/productList");
			}else {
				session.setAttribute("msg","登录失败,请检查用户账号和密码");  //账号密码导致登录失败
				System.out.println("登录失败");
				resp.sendRedirect(req.getContextPath()+"/login.html");
			}

		}else {
			session.setAttribute("msg","验证码输入错误");  //验证码 导致登录失败
			System.out.println("登录失败 验证码有问题");
			resp.sendRedirect(req.getContextPath()+"/login.html");
		}
	}
}
